/*
*   Copyright 2011 Matthew Crinklaw-Vogt
*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*  limitations under the License.
*/

package com.tantaman.util.concurrent;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashSet<E> implements Set<E> {
	private final Map<E, Object> mMap;
	private static final Object VALUE = new Object();
	
	public ConcurrentHashSet() {
		mMap = new ConcurrentHashMap<E, Object>();
	}

	@Override
	public int size() {
		return mMap.size();
	}

	@Override
	public boolean isEmpty() {
		return mMap.isEmpty();
	}

	@Override
	public boolean contains(Object o) {
		return mMap.containsKey(o);
	}

	@Override
	public Iterator<E> iterator() {
		return mMap.keySet().iterator();
	}

	@Override
	public Object[] toArray() {
		return mMap.keySet().toArray();
	}

	@Override
	public <T> T[] toArray(T[] a) {
		return mMap.keySet().toArray(a);
	}

	@Override
	public boolean add(E e) {
		mMap.put(e, VALUE);
		return true;
	}

	@Override
	public boolean remove(Object o) {
		mMap.remove(o);
		return true;
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		return mMap.keySet().containsAll(c);
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		for (E e : c) {
			mMap.put(e, VALUE);
		}
		
		return true;
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		Set<E> temp = new HashSet<E>();
		
		for (Object o : c) {
			if (mMap.containsKey(o)) {
				temp.add((E)o);
			}
		}
		
		clear();
		addAll(temp);
		
		return true;
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		for (Object o : c) {
			mMap.remove(o);
		}
		
		return true;
	}

	@Override
	public void clear() {
		mMap.clear();
	}
	
}
